package com.woniuxy.location.controller;

import com.woniuxy.commons.util.ResponseResult;
import com.woniuxy.commons.util.ResultStatus;
import com.woniuxy.location.service.LocationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Point;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.RoundingMode;
import java.text.DecimalFormat;

@RestController
@Slf4j
@RequestMapping("/location")
public class LocationController {
    DecimalFormat df = new DecimalFormat("#.000000");
    @Resource
    private LocationService locationService;

    @GetMapping("/distance/{disabledId}/{attendantId}")
    public ResponseResult getLocationAndDistance(@PathVariable("disabledId") int disabledId,@PathVariable("attendantId") int attendantId){
        //获取陪护员位置
        Point location = locationService.getAttendantLocation(attendantId);
        ResponseResult responseResult = new ResponseResult();
        if(null == location){
            responseResult.setCode(500);
            responseResult.setMsg("无法获取到陪护员位置");
            responseResult.setStatus(ResultStatus.FAIL);
            return responseResult;
        }
        log.info("陪护员位置："+location.toString() );
        // 计算二者距离
        Distance distance = locationService.getDistance(disabledId, attendantId);
        if(null == distance){
            responseResult.setCode(500);
            responseResult.setMsg("计算距离失败");
            responseResult.setStatus(ResultStatus.FAIL);
            return responseResult;
        }
        log.info(distance.toString());

        responseResult.setStatus(ResultStatus.SUCCESS);
        responseResult.setCode(200);
        responseResult.setMsg("查询成功");
        df.setRoundingMode(RoundingMode.DOWN);
        responseResult.setData(df.format(location.getX())+","+df.format(location.getY())+","+Math.round(distance.getValue()) );

        return responseResult;
    }
}
